import axios from "./base";
import qs from 'qs';

// import { useTabsStore } from "@/stores/modules/tabs";
// const tabStore = useTabsStore();
// import { ipcRenderer } from "electron";
const { VITE_CLIENT_TYPE } = import.meta.env;

export const loadLocalPage = (path, target) => {
  if (VITE_CLIENT_TYPE === "electron") {
    // ipcRenderer.invoke("load-url", path);
  } else if (path) {
    window.$ui.openWin(path, target);
  } else {
    window.location.reload()
  }
};
export const loadPage = (path, target) => {
  if (VITE_CLIENT_TYPE === "electron") {
    // ipcRenderer.invoke("open-win", path);
  } else {
    window.$ui.openWin(path, target);
  }
};
export const downLoadApp = (url, target) => {
  if (VITE_CLIENT_TYPE === "electron") {
    // ipcRenderer.invoke("download-app", url);
  } else {
    window.$ui.openWin(url, target);
  }
};
// 获取logo信息
export const getAppcatesortList = data => {
  return axios.post("/openapi-uc/appcatesort/list", data).then(res => {
    return res;
  });
};
// 获取logo信息
export const queryAllTypeByLang = data => {
  return axios({
    method: "post",
    url: "/openapi-uc/appType/queryAllTypeByLang",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded;"
    },
    data: qs.stringify({}),
    params: {
      ...data
    }
  }).then(res => {
    return res;
  });
};

// 获取第三方登录配置信息
export const getAppDownloadUrl = data => {
  return axios.get("/openapi-uc/app/" + data).then(res => {
    return res;
  });
};

// 获取用户信息
export const deletcollection = data => {
  return axios.post("/openapi-uc/app/v2/deletcollection", data).then(res => {
    return res;
  });
};

export const getcollection = data => {
  return axios
    .post("/openapi-uc/app/v2/getcollection", {
      ...data
    })
    .then(res => {
      return res;
    });
};

// 获取班级信息
export const collection = data => {
  return axios
    .post("/openapi-uc/app/v2/collection", {
      ...data
    })
    .then(res => {
      return res;
    });
};

// 获取任教信息
export const getAppRecentVisit = data => {
  let params = {
    startTime: "1999-01-01 00:00:00",
    ...data
  };
  Object.keys(params).forEach(key => {
    if (params[key] === "") {
      delete params[key];
    }
  });
  return axios
    .post("/openapi-uc/app/getAppRecentVisit", {
      ...params
    })
    .then(res => {
      return res;
    });
};

// 获取学生班级信息
export const getAppList = data => {
  return axios
    .post("/openapi-uc/app/auth/list", {
      ...data
    })
    .then(res => {
      return res;
    });
};

// 获取学生信息
export const searchApp = data => {
  return axios
    .post("/openapi-uc/sys/config/search", {
      ...data
    })
    .then(res => {
      return res;
    });
};

// 获取配置信息
export const getAppDetail = data => {
  return axios.get("/openapi-uc/app/" + data).then(res => {
    return res;
  });
};

// 获取二维码
export const queryDictItemList = data => {
  return axios({
    method: "post",
    url: `/openapi-base/base/queryDictItemList`,
    data: {
      ...data
    }
  }).then(res => {
    return res;
  });
};

// 获取扫码成功
export const getAccreditCode = data => {
  return axios({
    method: "post",
    url: `/openapi-uc/accreditcode/getAccreditCode`,
    data: {
      ...data
    }
  }).then(res => {
    return res;
  });
};

// 查询用户
export const addComment = data => {
  return axios
    .post("/openapi-uc/app/comment/add", {
      ...data
    })
    .then(res => {
      return res;
    });
};

// 查询顶级机构
export const getByEntity = data => {
  return axios.post("/openapi-uc/app/comment/getByEntity", { ...data }).then(res => {
    return res;
  });
};
// 查询子机构
export const joinSearch = data => {
  return axios.post("/openapi-uc/app/comment/joinSearch", { ...data }).then(res => {
    return res;
  });
};

// 按班级查询学生
export const queryDocMenuById = data => {
  return axios
    .post("/openapi-uc/docMenu/queryDocMenuById/", {
      ...data
    })
    .then(res => {
      return res;
    });
};

// 获取信任码
export const getAccrCode = (path, params, target) => {
  let token = window.$app.user.token;

  if (typeof params === "string") {
    target = params;
    params = null;
  }

  if (path && target !== "_self") {
    target = "_blank";
  }

  let requestParams = {
    accessToken: token,
    userId: window.$app.user.userId
  };

  if (params && params.authAppId) {
    // 添加域控参数
    requestParams.authAppId = params.authAppId;
    delete params.authAppId;
  }

  return axios
    .post("/openapi-uc/accreditcode/getAccreditCode", requestParams)
    .then(data => {
      let serverResult = data.serverResult;
      let responseEntity = data.responseEntity;

      if (serverResult.resultCode === "200" && responseEntity.accreditCode) {
        window.$app.setAuth(
          {
            accreditCode: responseEntity.accreditCode,
            accreditUrl: "accredit_code=" + responseEntity.accreditCode + "&access_token=" + token + "&token=" + token
          },
          true
        );

        if (path) {
          path =
            path +
            (path.indexOf("?") === -1 ? "?" : "&") +
            "accredit_code=" +
            responseEntity.accreditCode +
            "&access_token=" +
            token +
            "&token=" +
            token +
            (params ? "&" + window.$ui.qs.stringify(params) : "");

          // const tabsParams = {
          //   icon: "Menu",
          //   title: "Bing 内嵌",
          //   isLink: "",
          //   isHide: false,
          //   isFull: false,
          //   isAffix: false,
          //   path: path,
          //   name: path,
          //   close: true,
          //   isKeepAlive: true
          // };
          // tabStore.addTabs(tabsParams);
          // if (VITE_CLIENT_TYPE === "electron") {
          //   ipcRenderer.invoke("open-win", path);
          // } else {
          //   window.$ui.openWin(path, target);
          // }
          loadPage(path, target);
        } else {
          return responseEntity.accreditCode;
        }
      } else if (serverResult.resultCode === "10000") {
        window.$ui
          .msgBox({
            title: "请登录",
            type: "warning",
            message: "登录状态已过期，或在其他设备上登录！",
            confirmButtonText: "确定",
            showCancelButton: false,
            showClose: false
          })
          .then(() => {
            window.$ui.delAuth();
          });
      } else if (serverResult.resultCode === "8028") {
        window.$ui.msg(serverResult.resultMessage);
        return new Error("failed to get the acredit code.");
      } else {
        return new Error("failed to get the acredit code.");
      }
    })
    .catch(e => {
      console.error(e);
    });
};

export const openApp = (path, params, target) => {
  if (params && params.userToken) {
    axios
      .get(window.$app.ecoGateway + "/openapi-uc/oauth/checkToken?access_token=" + params.userToke)
      .then(() => {
        gotoUrl(path, target);
      })
      .catch(err => {
        console.log(err);
        getAccrCode(path, params, target);
      });
  } else {
    getAccrCode(path, params, target);
  }
};

export const gotoUrl = (url, target) => {
  if (/{accreditCode}$/.test(url)) {
    openApp(url.replace(/{accreditCode}$/, ""), null, target || "_self");
  } else {
    const toUrl = new URL(url, window.location.href);
    const toPath = toUrl.origin + toUrl.pathname;
    const currentPath = window.location.origin + window.location.pathname;

    if (toPath !== currentPath) {
      window.$ui.openWin(url, target);
    }
  }
};
